package com.spring.mvc.dao;

import com.spring.mvc.entity.Person;
import com.spring.mvc.entity.School;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * ${DESCRIPTION}
 *
 * @author roger
 * @email 190642964@qq.com
 * @create 2018-02-01 11:44
 **/
@Repository
public class SchoolDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据ID查询单个对象
     *
     * @param id 主键
     * @return School
     */
    public School selectById(Integer id) throws SQLException {
        Connection connection = jdbcTemplate.getDataSource().getConnection();
        final String sql = "select id,name from school where id = ?";
        return (School) jdbcTemplate.queryForObject(sql,new Object[]{id},new SchoolRowMapper());
    }

    class SchoolRowMapper implements RowMapper {
        @Override
        public Object mapRow(ResultSet rs ,int rowNum)throws SQLException {
            School school = new School();
            school.setId(rs.getInt("id"));
            school.setName(rs.getString("name"));
            return school;
        }
    }

    /**
     * 保存 School
     * @param name 名字
     */
    public void insertSchool(String name) throws SQLException {
        Connection connection = jdbcTemplate.getDataSource().getConnection();
        final String sql = "insert into school (name) values('" + name + "')";
        jdbcTemplate.execute(sql);
    }

}
